package com.th.coupon.executor.impl;

import com.th.coupon.common.vo.CouponTemplateSdk;
import com.th.coupon.common.vo.SettlementInfo;
import com.th.coupon.constant.RuleFlag;
import com.th.coupon.executor.AbstractRuleExecutor;
import com.th.coupon.executor.RuleExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 折扣优惠卷结算规则执行器
 * @author 涂航
 */
@Component
@Slf4j
public class DiscountExecutor extends AbstractRuleExecutor implements RuleExecutor {

    /**
     * 规则类型标记
     * @return
     */
    @Override
    public RuleFlag ruleConfig() {
        return RuleFlag.DISCOUNT_RULE;
    }

    /**
     * 优惠卷规则计算
     * @param info {@link SettlementInfo} 包含了选择的优惠卷
     * @return {@link SettlementInfo} 修正过的结算信息
     */
    @Override
    public SettlementInfo computeRule(SettlementInfo info) {
        //获取商品总计
        Double goodsSum = retain2Decimals(goodsCostSum(info.getGoodsInfos()),2);
        //效验商品类型与优惠卷限制不匹配的情况
        SettlementInfo settlementInfo = processGoodsTypeNatSatisfy(info, goodsSum);
        if(null != settlementInfo){
            log.debug("Discount Template Is Not Match GoodsType !");
            return settlementInfo;
        }

        //折扣优惠卷可以直接使用
        CouponTemplateSdk templateSdk = info.getCouponAndTemplateInfos().get(0).getTemplateSdk();

        //减去金额 折扣 额度
        Double quota = Double.valueOf(templateSdk.getRule().getDiscount().getQuota());
        //计算使用优惠卷之后的价格
        info.setCost(retain2Decimals((goodsSum * (quota*1.0/100)),2) > minCost() ?
                retain2Decimals((goodsSum * (quota*1.0/100)),2) : minCost()
        );
        log.debug("Use Discount Coupon Make Goods Cost From {} To {}",goodsSum,info.getCost());

        return info;
    }
}
